package com.geotmt.billingcenter.common.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description 生成、校验token的工具类
 * @Author      yanghanwei
 * @Mail        yanghanwei@geotmt.com
 * @Date        2019/3/18 19:15
 * @Version     v1
 **/
public class JwtUtil {

    private static final int TOKEN_REFRESH_INTERVAL = 1800;
    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的签发时间
     */
    public static Date getIssuedAt(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getIssuedAt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取用户id
     * @param token
     * @return
     */
    public static String getId(String token) throws Exception{
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getId();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获取 userId
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,expireTime后过期
     * @param username 用户名
     * @param time 过期时间s
     * @return 加密的token
     */
    public static String sign(String username, String salt, long time) {
        try {
            Date date = new Date(System.currentTimeMillis()+time*1000);
            Algorithm algorithm = Algorithm.HMAC256(salt);
            // 附带username信息
            return JWT.create()
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .withIssuedAt(new Date())
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    public static Date getExpiresAt(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getExpiresAt();
        }catch(JWTDecodeException e){
            return null;
        }
    }

    /**
     * token是否过期
     * @return true：过期
     */
    public static boolean isTokenExpired(String token) throws Exception{
        Date now = Calendar.getInstance().getTime();
        DecodedJWT jwt = JWT.decode(token);
        if(null == jwt){
            return false;
        }
        return jwt.getExpiresAt().before(now);
    }


    /**
     * 是否需要刷新
     * @param expireAt
     * @return
     */
    public static boolean shouldTokenRefresh(Date expireAt){
        if(null==expireAt){
            return true;
        }
        LocalDateTime issueTime = LocalDateTime.ofInstant(expireAt.toInstant(), ZoneId.systemDefault());
        return LocalDateTime.now().isAfter(issueTime.minusSeconds(TOKEN_REFRESH_INTERVAL));
    }
}
